const socket = new WebSocket('ws://localhost:3000');
const progressElement = document.getElementById('progress');
socket.onopen = () => {
  console.log('WebSocket connected');
};

socket.onmessage = (event) => {
  const data = JSON.parse(event.data);
  
  progressElement.innerText = `转换进度：${data.progress}%`;
  console.log(event)
  if (data.event === 'conversionComplete') {
    progressElement.innerText = `转换进度：100%`;
  }
};

socket.onclose = () => {
  console.log('WebSocket disconnected');
};

document.getElementById('uploadForm').addEventListener('submit', (event) => {
  event.preventDefault();

  const fileInput = document.getElementById('fileInput');
  const file = fileInput.files[0];

  if (file) {
    const formData = new FormData();
    formData.append('file', file);

    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/upload', true);
    xhr.upload.addEventListener('progress', (event) => {
      if (event.lengthComputable) {
        const percent = (event.loaded / event.total) * 100;
        progressElement.innerText = `上传进度：${percent.toFixed(2)}%`;
      }
    });

    xhr.onreadystatechange = () => {
      if (xhr.readyState === XMLHttpRequest.DONE) {
        if (xhr.status === 200) {
            var obj = JSON.parse(xhr.responseText)
            console.log(obj)
            document.getElementById("result").style.display = "block";
            document.getElementById("downloadLink").innerHTML = obj.downloadLink
            document.getElementById("downloadLink").href = obj.downloadLink
          console.log('文件上传成功');
        } else {
          console.error('文件上传失败');
        }
      }
    };

    xhr.send(formData);
  }
});